package com.hgsoft.service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.hgsoft.dao.ModuleDao;
import com.hgsoft.entity.Module;
import com.hgsoft.util.Property;
import com.hgsoft.util.Order;

@Service 
public class ModuleService extends BaseService<Module>{

	Order[] orders = new Order[]{Order.asc("level"),Order.asc("priority")};
	
	@Override
	public List<Module> findAll(){
		return getDao().findAll(orders);
	}
	
	public List<Module> findChildren(Integer id){
		return getDao().findAll(orders, Property.eq("parent.id", id));
	}
	
	public List<Module> findByLevel(Integer id){
		return getDao().findAll(orders, Property.gt("level", id));
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public List<Module> getMenus(HashSet<Module> set){
		List list = new ArrayList();
		if(set!=null && !set.isEmpty()){
			Iterator it = set.iterator();
			while(it.hasNext()){
				Module module = (Module)it.next();
				list.add(module.getId());
			}
		}
		return getDao().findAll(orders, Property.eq("display", 1), Property.in("id", list));
	}
	
	public String getCurrentPosition(Integer id){
		String position = "";
		Module module = getDao().find(id);
		if(module != null){
			position = module.getName();
			while(module.getParent() != null){
				module = module.getParent();
				if(module != null){
					position = module.getName() + " > " + position;
				}
			}
		}
		return position;
	}
	
	@Resource(type=ModuleDao.class)
	public void setDao(ModuleDao dao){
		super.setDao(dao);
	}	
}
